#!/bin/bash

# 一键HTTPS配置脚本
# 简化版本，用于快速配置HTTPS

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印标题
print_title() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "    Pecco宠物用品网站 HTTPS配置工具"
    echo "=================================================="
    echo -e "${NC}"
}

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查运行环境
check_environment() {
    log_info "检查运行环境..."
    
    # 检查是否为root用户
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用root权限运行此脚本: sudo $0"
        exit 1
    fi
    
    # 检查Docker是否运行
    if ! docker ps &> /dev/null; then
        log_error "Docker未运行或无权限访问，请检查Docker状态"
        exit 1
    fi
    
    # 检查docker-compose是否存在
    if ! command -v docker-compose &> /dev/null; then
        log_error "未找到docker-compose命令"
        exit 1
    fi
    
    log_info "环境检查通过"
}

# 获取用户输入
get_user_input() {
    log_info "请输入配置信息..."
    
    # 获取域名
    while [ -z "$DOMAIN" ]; do
        echo -n "请输入您的域名 (例如: pecco.pet): "
        read DOMAIN
        if [ -z "$DOMAIN" ]; then
            log_warn "域名不能为空"
        fi
    done
    
    # 获取邮箱
    while [ -z "$EMAIL" ]; do
        echo -n "请输入您的邮箱 (用于Let's Encrypt通知): "
        read EMAIL
        if [ -z "$EMAIL" ]; then
            log_warn "邮箱不能为空"
        fi
    done
    
    # 确认信息
    echo
    log_info "配置信息确认:"
    echo "域名: $DOMAIN"
    echo "邮箱: $EMAIL"
    echo
    echo -n "确认配置信息正确吗? (y/N): "
    read confirm
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        log_info "配置已取消"
        exit 0
    fi
}

# 检查域名解析
check_domain_resolution() {
    log_info "检查域名解析..."
    
    # 获取服务器公网IP
    SERVER_IP=$(curl -s ifconfig.me || curl -s ipinfo.io/ip || echo "unknown")
    
    if [ "$SERVER_IP" = "unknown" ]; then
        log_warn "无法获取服务器公网IP，请手动检查域名解析"
        return
    fi
    
    log_info "服务器公网IP: $SERVER_IP"
    
    # 检查域名解析
    DOMAIN_IP=$(dig +short $DOMAIN | tail -n1)
    WWW_DOMAIN_IP=$(dig +short www.$DOMAIN | tail -n1)
    
    if [ "$DOMAIN_IP" = "$SERVER_IP" ]; then
        log_info "$DOMAIN 解析正确"
    else
        log_warn "$DOMAIN 解析可能有问题 (解析到: $DOMAIN_IP)"
    fi
    
    if [ "$WWW_DOMAIN_IP" = "$SERVER_IP" ]; then
        log_info "www.$DOMAIN 解析正确"
    else
        log_warn "www.$DOMAIN 解析可能有问题 (解析到: $WWW_DOMAIN_IP)"
    fi
}

# 配置HTTPS
configure_https() {
    log_info "开始配置HTTPS..."

    # 导出环境变量
    export DOMAIN
    export EMAIL

    # 首先尝试为主域名和www子域名同时获取证书
    log_info "尝试为 $DOMAIN 和 www.$DOMAIN 获取证书..."

    # 停止nginx容器以释放80端口
    docker-compose -f docker-compose.prod.yml stop nginx || true

    # 尝试获取包含两个域名的证书
    if certbot certonly \
        --standalone \
        --non-interactive \
        --agree-tos \
        --email "$EMAIL" \
        -d "$DOMAIN" \
        -d "www.$DOMAIN"; then

        log_info "成功获取包含两个域名的证书"

        # 复制证书
        cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem ./ssl-certs/
        cp /etc/letsencrypt/live/$DOMAIN/privkey.pem ./ssl-certs/
        chmod 644 ./ssl-certs/fullchain.pem
        chmod 600 ./ssl-certs/privkey.pem

    else
        log_warn "获取包含两个域名的证书失败，尝试只获取主域名证书..."

        # 降级：只获取主域名证书
        if certbot certonly \
            --standalone \
            --non-interactive \
            --agree-tos \
            --email "$EMAIL" \
            -d "$DOMAIN"; then

            log_info "成功获取主域名证书"

            # 复制证书
            cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem ./ssl-certs/
            cp /etc/letsencrypt/live/$DOMAIN/privkey.pem ./ssl-certs/
            chmod 644 ./ssl-certs/fullchain.pem
            chmod 600 ./ssl-certs/privkey.pem

        else
            log_error "SSL证书获取失败"
            exit 1
        fi
    fi
}

# 配置自动续期
setup_auto_renewal() {
    log_info "配置SSL证书自动续期..."
    
    # 获取当前脚本的绝对路径
    SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
    
    # 更新续期脚本中的路径
    if [ -f "./renew-ssl.sh" ]; then
        sed -i "s|PROJECT_DIR=\"/path/to/pecco-pet-shop\"|PROJECT_DIR=\"$SCRIPT_DIR\"|g" ./renew-ssl.sh
        sed -i "s|DOMAIN=\"pecco.pet\"|DOMAIN=\"$DOMAIN\"|g" ./renew-ssl.sh
        
        # 添加到crontab
        CRON_JOB="0 2 * * * $SCRIPT_DIR/renew-ssl.sh >> /var/log/ssl-renewal.log 2>&1"
        
        # 检查crontab中是否已存在
        if ! crontab -l 2>/dev/null | grep -q "$SCRIPT_DIR/renew-ssl.sh"; then
            (crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
            log_info "已添加SSL证书自动续期定时任务"
        else
            log_info "SSL证书自动续期定时任务已存在"
        fi
    else
        log_warn "未找到renew-ssl.sh脚本，请手动配置自动续期"
    fi
}

# 验证配置
verify_configuration() {
    log_info "验证HTTPS配置..."
    
    # 等待服务启动
    sleep 15
    
    # 测试HTTP重定向
    if curl -s -I "http://$DOMAIN" | grep -q "301\|302"; then
        log_info "✓ HTTP到HTTPS重定向正常"
    else
        log_warn "✗ HTTP重定向可能有问题"
    fi
    
    # 测试HTTPS连接
    if curl -s -I "https://$DOMAIN" | grep -q "200"; then
        log_info "✓ HTTPS连接正常"
    else
        log_warn "✗ HTTPS连接可能有问题"
    fi
    
    # 显示SSL证书信息
    if command -v openssl &> /dev/null; then
        log_info "SSL证书信息:"
        echo | openssl s_client -connect $DOMAIN:443 -servername $DOMAIN 2>/dev/null | openssl x509 -noout -dates
    fi
}

# 显示完成信息
show_completion_info() {
    echo
    echo -e "${GREEN}=================================================="
    echo "           HTTPS配置完成！"
    echo "==================================================${NC}"
    echo
    echo "您的网站现在可以通过以下地址访问:"
    echo "• HTTPS: https://$DOMAIN"
    echo "• HTTPS: https://www.$DOMAIN"
    echo "• HTTP会自动重定向到HTTPS"
    echo
    echo "SSL证书信息:"
    echo "• 证书提供商: Let's Encrypt"
    echo "• 有效期: 90天"
    echo "• 自动续期: 已配置 (每天凌晨2点检查)"
    echo
    echo "建议的后续操作:"
    echo "1. 使用SSL Labs测试您的配置: https://www.ssllabs.com/ssltest/"
    echo "2. 检查安全头配置: https://securityheaders.com/"
    echo "3. 定期检查证书续期日志: /var/log/ssl-renewal.log"
    echo
}

# 主函数
main() {
    print_title
    check_environment
    get_user_input
    check_domain_resolution
    configure_https
    setup_auto_renewal
    verify_configuration
    show_completion_info
}

# 运行主函数
main "$@"
